package com.app.interceptor;


import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import com.app.exception.BaseException;
import com.app.model.SysUser;
import com.app.model.User;
import com.app.service.ISysUserService;
import com.app.service.IUserService;
import com.app.service.Impl.SysUserServiceImpl;
import com.app.service.Impl.UserServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Component
public class SpringbootInterceptor implements HandlerInterceptor {

//    @Autowired
//    private UserServiceImpl userService;
//
//    @Autowired
//    private SysUserServiceImpl sysUserService;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {

    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //刷新过期时间
        String token = request.getHeader("token");
         //++logger.info(request.getRequestURI());
         //++logger.info(request.getQueryString());

        List<String> openPaths = Arrays.asList(
                "/api/adminUser/captcha"
        );

        //物联网设备推送接口放行
        String uri = request.getRequestURI();

        System.err.println("当前请求uri: " + uri);

//        if (1==1){
//            return true;
//        }

        //登录接口，放行
        if (uri.contains("/login") || uri.contains("getUserCode") || uri.contains("captcha") || uri.contains("/appletLoginTest") || uri.contains("/tokenTest")
                || uri.contains("/getAdminRole") || uri.contains("/getMenuList")) {

            return true;
        }

        //文件，放行
        if (uri.contains("/file/") || uri.contains("/template/")){
            return true;
        }

        //swagger相关接口放行
        if (uri.contains("/api/doc.html") || uri.contains("/swagger-ui/index.html") || uri.contains("/swagger-ui/**")
                || uri.contains("/swagger-ui.html**") || uri.contains("swagger-resources") || uri.contains("/v3/api-docs")|| uri.contains("/webjars/")
                || uri.contains("/favicon.ico")){
            return true;
        }

        //自定义接口放行
        if (uri.contains("/adminGetDicList") || uri.contains("/getOpenid") || uri.contains("/getPhone")){
            return true;
        }

        //测试接口用
        if(1==1){
            return true;
        }

        if(token == null){
            throw new BaseException(401, "用户未登录");
        }else {

//            if (null==sysUserService) {//解决service为null无法注入问题
//                BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
//                sysUserService = (SysUserServiceImpl) factory.getBean("sysUserServiceImpl");
//            }
//            if (null==userService) {//解决service为null无法注入问题
//                BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
//                userService = (UserServiceImpl) factory.getBean("userServiceImpl");
//            }
            String userId = StpUtil.getLoginIdByToken(token).toString();

            String loginType = (String) StpUtil.getSession().get("loginType");
            System.err.println("当前登录类型: " + loginType);
            System.err.println("当前登录用户id: " + userId);
            if ("admin".equals(loginType)){
//                QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("id", userId);
//                SysUser sysUser = sysUserService.getOne(queryWrapper);
//                if (sysUser == null){
//                    throw new BaseException(401, "用户不存在");
//                }
            }else if ("user".equals(loginType)){
//                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("id", userId);
//                User user = userService.getOne(queryWrapper);
//                if (user == null){
//                    throw new BaseException(401, "用户不存在");
//                }
            }
        }
        return true;
    }

}